package br.pucrs.lognplay.service;

import java.util.List;

import javax.ejb.Stateless;

import br.pucrs.lognplay.entity.User;
import br.pucrs.lognplay.repository.RepositoryManager;
import br.pucrs.lognplay.repository.UserRepository;

@Stateless
public class UserManagementServiceBean implements UserManagementService {

	public void mergeUser(User user) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			UserRepository userRepository = RepositoryManager.getUserRepository();
			userRepository.merge(user);
			RepositoryManager.commitTransaction();
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on merge an user", e);
		}
	}

	public User getUserById(String id) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			UserRepository userRepository = RepositoryManager.getUserRepository();
			User user = userRepository.get(id);
			RepositoryManager.commitTransaction();
			return user;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on get an user by id", e);
		}
	}

	public User getUserByUsername(String username) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			UserRepository userRepository = RepositoryManager.getUserRepository();
			User user = userRepository.getByUsername(username);
			RepositoryManager.commitTransaction();
			return user;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on get an user by username", e);
		}
	}

	public List<User> listAllUsers() throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			UserRepository userRepository = RepositoryManager.getUserRepository();
			List<User> users = userRepository.listAll();
			RepositoryManager.commitTransaction();
			return users;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list all users", e);
		}
	}

	public List<User> listUsersByClientId(String clientId) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			UserRepository userRepository = RepositoryManager.getUserRepository();
			List<User> users = userRepository.listByClientId(clientId);
			RepositoryManager.commitTransaction();
			return users;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list users by client id", e);
		}
	}
}
